package com.fenghongzhang.module_user.login

import com.fenghongzhang.lib_base.core.BaseViewModel
import com.fenghongzhang.lib_common.mmkv.MMKVOwner
import com.fenghongzhang.module_user.mmkv.UserMMKV
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject


@HiltViewModel
class LoginViewModel @Inject constructor(val repository: LoginRepository) : BaseViewModel<LoginState, LoginIntent>(LoginState()) {


    //5, 具体处理的逻辑
    override suspend fun handleEvent(event: LoginIntent) {
        when (event) {
            is LoginIntent.UsernameChanged -> updateState(state.value.copy(userName = event.username))
            is LoginIntent.PasswordChanged -> updateState(state.value.copy(password = event.password))

            // 6, 登录点击事件
            is LoginIntent.LoginClicked -> performLogin()
        }
    }

    //7, 登录点击事件处理
    private suspend fun performLogin() {
        val state =  state.value
        if (state.userName?.isEmpty() == true || state.password?.isEmpty() == true) {
            updateState(state.copy(error = "用户名和密码不能为空"))
            return
        }
        updateState(state.copy(isLoading = true, error = null))

        // 8, 调用登录接口
        val result = state.userName?.let { state.password?.let { it1 -> repository.login(it, it1) } }
        updateState(state.copy(isLoading = false))


        //17, 处理登录结果
        result?.onSuccess { loginState ->
            if (loginState.isSucess) {
                // 登录成功逻辑，这里可以导航到主界面
                // 实际项目中应该通过回调或Event通知View
                println("登录成功")
                UserMMKV.accessToken = loginState.userInfo?.token ?: ""
                println(UserMMKV.accessToken)
                // 18, 更新状态
                updateState(state.copy(userInfo = loginState.userInfo, isSucess = true))
            }
        }?.onFailure { error ->
            updateState(state.copy(error = error.message))
        }
    }
}